package com.xx.doublexchat.common.chat.service.impl;

import com.xx.doublexchat.common.chat.dao.RoomDao;
import com.xx.doublexchat.common.chat.dao.RoomFriendDao;
import com.xx.doublexchat.common.chat.domain.entity.Room;
import com.xx.doublexchat.common.chat.domain.entity.RoomFriend;
import com.xx.doublexchat.common.chat.domain.enums.RoomTypeEnum;
import com.xx.doublexchat.common.chat.service.IRoomService;
import com.xx.doublexchat.common.chat.service.adapter.ChatAdapter;
import com.xx.doublexchat.common.common.utils.AssertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class RoomServiceImpl implements IRoomService {

    @Autowired
    private RoomFriendDao roomFriendDao;

    @Autowired
    private RoomDao roomDao;

    @Override
    public RoomFriend createFriendRoom(List<Long> uidList) {
        AssertUtils.isNotEmpty(uidList, "房间创建失败，好友数量不对");
        AssertUtils.equal(uidList.size(), 2, "房间创建失败，好友数量不对");
        String key = ChatAdapter.generateRoomKey(uidList);

        RoomFriend roomFriend = roomFriendDao.getByKey(key);
        if (Objects.nonNull(roomFriend)) {
            //如果存在房间就恢复，适用于恢复好友场景
            restoreRoomIfNeed(roomFriend);
        } else {
            //新建房间
            Room room = createRoom(RoomTypeEnum.FRIEND);
            roomFriend = createFriendRoom(room.getId(), uidList);
        }
        return roomFriend;
    }

    @Override
    public void disableFriendRoom(List<Long> uidList) {
        AssertUtils.isNotEmpty(uidList, "房间创建失败，好友数量不对");
        AssertUtils.equal(uidList.size(), 2, "房间创建失败，好友数量不对");
        String key = ChatAdapter.generateRoomKey(uidList);
        roomFriendDao.disableRoom(key);
    }

    /**
     * 创建好友信息
     * @param roomId 房间id
     * @param uidList 好友id集合
     * @return
     */
    private RoomFriend createFriendRoom(Long roomId, List<Long> uidList) {
        return null;
    }

    /**
     * 创建房间
     * @param typeEnum 房间类型
     * @return
     */
    private Room createRoom(RoomTypeEnum typeEnum) {
        Room insert = ChatAdapter.buildRoom(typeEnum);
        roomDao.save(insert);
        return insert;
    }

    /**
     * 恢复好友
     * @param roomFriend
     */
    private void restoreRoomIfNeed(RoomFriend roomFriend) {

    }
}
